var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 验收表
    contract: [],

    // 实际铺贴面积
    ares: "",
    // 单价
    price: "",
    // 金额
    amount: "",
    // 用胶量
    consumption: "",
    // 厚度
    thickness: "",
    // 浆层厚度照片
    thicknessList: [],
    issuccessMask: false,
    tonzhi: false,
    typeIndex: 0,
    workList: [],
  },
  HidedispatcCarer() {
    this.setData({
      tonzhi: false
    })
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。\\
    prevPage.getOrderDetails()
    prevPage.setData({
      todo: ''
    })
    wx.navigateBack({
      delta: 1,
    })

  },
  // 上传附件
  upload(arr) {
    return new Promise((reslove, reject) => {
      if (arr.length == 0) {
        reslove([])
        return
      }
      wx.showLoading({
        title: '上传中...', //提示的内容
        mask: true //显示透明蒙层 防止触摸穿透
      })
      let finishFilesList = []
      arr.forEach((item, index) => {
        wx.uploadFile({
          url: app.globalData.Interfaceurl + 'saveFileUpload',
          filePath: item,
          name: 'file',
          formData: {
            userId: app.globalData.userId,

          },
          header: {
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            finishFilesList.push(JSON.parse(res.data).fileUrl)
            if (index >= arr.length - 1) {
              setTimeout(()=>{
                wx.hideLoading();
                reslove(finishFilesList)
               },500)
            }
          },
          fail: err => {
            return err
          }
        })
      })
    })
  },
  showmask() {
    if (wx.getStorageSync('up') == false) {
      wx.setStorageSync('up', true)
      setTimeout(() => {
        wx.setStorageSync('up', false)
      }, 1000);
      let workList = []
      this.data.workList.forEach(item => {
        let obj = {
          workId: item.id,
          token: app.token(),
          superviseCheckProof: item.oldsuperviseCheckProof == "" ? [] : item.oldsuperviseCheckProof,
          bricklayPaySize: item.bricklayPaySize,
          bricklayPayAmount: item.bricklayPayAmount,
          bricklayGlueDosage: item.bricklayGlueDosage,
          bricklaySlurryThickness: item.bricklaySlurryThickness,
          bricklaySlurryThicknessProof: item.bricklaySlurryThicknessProof == "" ? [] : item.bricklaySlurryThicknessProof,
          bricklayActualEndDate: item.bricklayActualEndDate,
          bricklayActualDuration: item.bricklayActualDuration,
          bricklayPlaceProof: item.bricklayPlaceProof == "" ? [] : item.bricklayPlaceProof,
          bricklayPanoramaProof: item.bricklayPanoramaProof == "" ? [] : item.bricklayPanoramaProof,
          bricklaySpecificProof: item.bricklaySpecificProof == "" ? [] : item.bricklaySpecificProof,
          workType: item.workType,
          bricklayUnitName: item.bricklayUnitName
        }
        workList.push(obj)
      })
      let arr
      if (this.data.typeIndex == 0) {
        arr = workList.filter(item => item.workType == 1)
        console.log(arr)
        // if (arr.some(item => item.superviseCheckProof.length == 0)) {
        //   wx.showToast({
        //     title: '请上传验收表',
        //     icon: 'none'
        //   })
        //   return
        // }
        if (arr.some(item => item.bricklayUnitName == "m²" && item.bricklayPaySize == '')) {
          wx.showToast({
            title: '请填写实际铺贴面积',
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          return
        }
        // if (arr.some(item => item.bricklayGlueDosage == '')) {
        //   wx.showToast({
        //     title: '请填写瓷砖胶用量',
        //     icon: 'none'
        //   })
        //   return
        // }
        if (arr.some(item => item.bricklaySlurryThickness == '')) {
          wx.showToast({
            title: '请填写浆层厚度',
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          return
        }
        if (arr.some(item => item.bricklaySlurryThicknessProof.length == 0)) {
          wx.showToast({
            title: '请上传浆层厚度图',
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          return
        }
        // if (arr.some(item => item.bricklayPlaceProof.length == 0)) {
        //   wx.showToast({
        //     title: '请上传各位置图',
        //     icon: 'none'
        //   })
        //   return
        // }

        // if (arr.some(item => item.bricklaySpecificProof.length == 0)) {
        //   wx.showToast({
        //     title: '请上传细节图',
        //     icon: 'none'
        //   })
        //   return
        // }

      } else if (this.data.typeIndex == 1) {

        arr = workList.filter(item => item.workType == 2)
        // if (arr.some(item => item.superviseCheckProof.length == 0)) {
        //   wx.showToast({
        //     title: '请上传验收表',
        //     icon: 'none'
        //   })
        //   return
        // }
        // if (arr.bricklaySpecificProof.length >= 3) {
        //   wx.showToast({
        //     title: '请上传细节图',
        //     icon: 'none'
        //   })
        //   return
        // }
        // if (arr.some(item => item.bricklayPanoramaProof.length == 0)) {
        //   wx.showToast({
        //     title: '请上传全景图',
        //     icon: 'none'
        //   })
        //   return
        // }



      } else {
        arr = workList.filter(item => item.workType == 3)
        // if (arr.some(item > item.bricklaySpecificProof.length >= 3)) {
        //   // if (arr.superviseCheckProof.length == 0) {
        //   //   wx.showToast({
        //   //     title: '请上传验收表',
        //   //     icon: 'none'
        //   //   })
        //   //   return
        //   // }
        //   wx.showToast({
        //     title: '请上传细节图',
        //     icon: 'none'
        //   })
        //   return
        // }
        // if (arr.some(item => item.bricklayPanoramaProof.length == 0)) {
        //   wx.showToast({
        //     title: '请上传全景图',
        //     icon: 'none'
        //   })
        //   return
        // }
      }

      arr.forEach(async (item, index) => {

        item.superviseCheckProof = await this.upload(item.superviseCheckProof)
        item.bricklaySlurryThicknessProof = await this.upload(item.bricklaySlurryThicknessProof)
        item.bricklayPlaceProof = await this.upload(item.bricklayPlaceProof)
        item.bricklayPanoramaProof = await this.upload(item.bricklayPanoramaProof)
        item.bricklaySpecificProof = await this.upload(item.bricklaySpecificProof)
        console.log(item)

        await this.saveSuperviseCheck(item).then((res) => {
          if (index == arr.length - 1 && res == 0) {
            wx.hideLoading();
            this.getOrderDetails(true)
          }
        })

      })
    }
  },
  // 项目详情接口
  getOrderDetails(showmak) {
    let t = this
    wx.showLoading({
      title: '加载中。。。', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'getOrderDetails',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        // userId: 1569562832576524288,
        orderId: t.data.orderId,
      },
      success: res => {
        wx.hideLoading();
        let workList = res.data.workList.filter(item => item.userId == t.data.userId)
        workList.forEach(item => {
          item.bricklayActualDuration = t.timediff(item.bricklayBeginDate, t.data.nowday)
          item.bricklayActualEndDate = t.data.nowday
          item.oldsuperviseCheckProof = []
          if (item.bricklayUnitName == "天") {
            // 
            item.bricklayPayAmount = item.bricklayActualDuration * item.bricklayUnitPrice
          } else {
            //  bricklayPaySize
            item.bricklayPayAmount = item.bricklayPaySize * item.bricklayUnitPrice
          }
          if (item.bricklaySlurryThicknessProof == '') {
            item.bricklaySlurryThicknessProof = []
          } else {
            item.bricklaySlurryThicknessProof = (item.bricklaySlurryThicknessProof.split(",")).map(item1 => t.data.Imageurl + item1)

          }
        })
        console.log(workList)
        t.setData({
          workList: workList,

        })

        if (this.data.workList.length != 0) {
          this.setData({
            typeIndex: workList[0].workType - 1
          })
        }



        if (showmak == true) {
          if (res.data.workList.some(item => item.inCheckDate == '')) {
            this.setData({
              issuccessMask: true
            })
          } else {
            this.setData({
              tonzhi: true
            })

          }
        }



      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },
  HidedispatcCar() {


    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。\\





    this.setData({
      issuccessMask: false,
      todo: 'previewacceptance'
    })
    wx.setStorageSync('istab', true)
    wx.navigateBack({
      delta: 1,
    })

    this.getOrderDetails()
  },
  goorderdectio() {
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。\\
    prevPage.setData({
      todo: ''
    })
    wx.navigateTo({
      url: '/pages/projectDetails/projectDetails?orderId=' + this.data.orderId,
    })
  },







  Unplonecontract(e) {
    let index = e.currentTarget.dataset.index
    let todo = e.currentTarget.dataset.todo
    let workList = this.data.workList
    workList[index][todo] = e.detail
    this.setData({
      workList: workList
    })

  },

  Unplonethickness(e) {

    let index = e.currentTarget.dataset.index
    let todo = e.currentTarget.dataset.todo
    let workList = this.data.workList
    workList[index][todo] = e.detail
    this.setData({
      workList: workList
    })
  },

  saveSuperviseCheck(obj) {
    let t = this
    wx.showLoading({
      title: '加载中。。。', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    return new Promise((reslove, reject) => {
      wx.request({
        url: app.globalData.Interfaceurl + 'saveSuperviseCheck',
        method: "post",
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        data: {
          userId: app.globalData.userId,
          workId: obj.workId,
          token: obj.token,
          orderId: t.data.orderId,
          superviseCheckProof: obj.superviseCheckProof.join(","),
          bricklayPaySize: obj.bricklayPaySize,
          bricklayPayAmount: obj.bricklayPayAmount,
          bricklayGlueDosage: obj.bricklayGlueDosage,
          bricklaySlurryThickness: obj.bricklaySlurryThickness,
          bricklaySlurryThicknessProof: obj.bricklaySlurryThicknessProof.join(","),
          bricklayActualEndDate: obj.bricklayActualEndDate,
          bricklayActualDuration: obj.bricklayActualDuration,
          bricklayPlaceProof: obj.bricklayPlaceProof.join(),
          bricklayPanoramaProof: obj.bricklayPanoramaProof.join(),
          bricklaySpecificProof: obj.bricklaySpecificProof.join()
        },
        success: res => {

          if (res.data.result == 0) {
            reslove(res.data.result)
          } else {
            wx.showToast({
              title: res.data.message,
              duration: 2500, //持续的时间
              icon: 'none', //图标
            })
            t.setData({
              token: t.token()
            })
          }




        },
        fail: err => {
          wx.showToast({
            title: '请求失败',
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
        }
      })
    })
  },


  // 铺贴面积失去焦点

  bindarea() {
    if (this.data.area == '') {

      return
    }

    let price = this.data.price

    if (price == '') {
      this.setData({
        amount: 0
      })
    } else {
      price = price - 0
      let amount = this.data.ares * price.toFixed(2)
      this.setData({
        amount: amount.toFixed(2)
      })
    }


  },
  // 单价失去焦点
  bindprice() {
    if (this.data.price == '') {
      return
    }
    let price = this.data.price - 0
    this.setData({
      price: price.toFixed(2),

    })
    if (this.data.ares == '') {
      this.setData({
        totalAmount: 0
      })
    } else {
      let amount = this.data.ares * this.data.price
      this.setData({
        amount: amount.toFixed(2)
      })
    }
  },
  bindtype(e) {
    let typeIndex = e.currentTarget.dataset.type
    this.setData({
      typeIndex: typeIndex
    })
  },


  //计算两个时间差  返回天小时分钟
  timediff(begin_time, end_time) {
    //年月日时分秒转换为时间戳
    let beginTime = (new Date(begin_time).getTime()) / 1000;
    let endTime = (new Date(end_time).getTime()) / 1000;
    var starttime = ''
    var endtime = ''
    if (beginTime < endTime) {
      starttime = beginTime;
      endtime = endTime;
    } else {
      starttime = endTime;
      endtime = beginTime;
    }
    //计算天数
    var timediff = endtime - starttime;
    var days = Math.floor(timediff / 86400) + 1;
    // //计算小时数
    // var remain = timediff % 86400;
    // var hours = parseInt(remain / 3600);
    //计算分钟数
    // var remain = remain % 3600;
    // var mins = parseInt(remain / 60);
    // var res = days + '天' + hours + '小时' + mins + '分';
    return days;
  },
  bindDateChange(e) {
    let index = e.currentTarget.dataset.index
    let workList = this.data.workList
    workList[index].bricklayActualEndDate = e.detail.value
    workList[index].bricklayActualDuration = this.timediff(workList[index].bricklayBeginDate, workList[index].bricklayActualEndDate)
    if (workList[index].bricklayUnitName == "天") {
      // 
      workList[index].bricklayPayAmount = workList[index].bricklayActualDuration * workList[index].bricklayUnitPrice
    } else {
      workList[index].bricklayPayAmount = workList[index].bricklayBudgetSize * workList[index].bricklayUnitPrice
    }



    this.setData({
      workList: workList
    })
  },
  jianchen(e) {
    let index = e.currentTarget.dataset.index
    let todo = e.currentTarget.dataset.todo
    let workList = this.data.workList

    workList[index][todo] = e.detail.value
    if (todo == "bricklayPaySize") {
      workList[index].bricklayPayAmount = workList[index].bricklayBudgetSize * workList[index].bricklayUnitPrice
    }
    this.setData({
      workList: workList
    })
  },
  fakeCallback() { },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    let date = new Date()
    let year = date.getFullYear()
    let mouth = date.getMonth() + 1
    mouth = mouth >= 10 ? mouth : "0" + mouth
    let d = date.getDate()
    d = d >= 10 ? d : "0" + d
    let nowday = year + "-" + mouth + "-" + d

    // let workList = JSON.parse(options.workList)







    this.setData({
      orderId: options.orderId,
      nowday: nowday,
      userId: options.userId,
      token: app.token(),
      Imageurl: app.globalData.Imageurl,
      // workList: workList,
    })


    this.getOrderDetails()
    if (options.todo) {
      this.setData({
        todo: options.todo
      })
    }
    if (options.todo == 'previewacceptance') {
      this.getOrderDetails()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.setStorageSync('up', false)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    wx.removeStorageSync("up")
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.removeStorageSync("up")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})